const tips = {
  1:'抱歉，出现了一个错误',
  1005:'appkey不存在，请前往小程序后台申请'
}

const debug = true

class HTTP{
  //  通用请求
  doRequest(url, params, method, onSuccess = null, onFailed = null, onResponse = null) {

    let startDate = new Date();

    if(debug){
      console.log('请求url：' + url);
      console.log('请求参数：' + JSON.stringify(params));
    }
    
    wx.request({
      url: url,
      data: params,
      method: method,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        // wx.hideLoading();

        let responseData = res.data
        let code = responseData.ret
        if(debug){
          console.log('请求结果：' + JSON.stringify(responseData));
        }
        
        if (code == 1 && onSuccess != null) {
          let result = responseData.data
          onSuccess(result)
        }
        else {
          if (onFailed != null){
            let msg = responseData.msg
            onFailed(msg)
          }
          else {
            wx.showToast({
              icon: 'none',
              title: '系统繁忙请联系客服'
            })
          }
        }

        if (onResponse != null) {
          onResponse(responseData)
        }
      },
      fail: function (err) {
        // wx.hideLoading();
        if (onFailed != null) {
          onFailed(err)
        }
      }
    })
  }
  //  GET请求
  doGetRequest(url, params, onSuccess = null, onFailed = null, onResponse = null){
    this.doRequest(url, params, "GET", onSuccess, onFailed, onResponse)
  }
  //  POST请求
  doPostRequest(url, params, onSuccess = null, onFailed = null, onResponse = null) {
    this.doRequest(url, params, "POST", onSuccess, onFailed, onResponse)
  }
  //显示错误信息
  _show_error(err_code){
    wx.showToast({
      title: tips[err_code],
      icon:'none',
      duration:1500
    })
  }
}

export{
  HTTP
}